//
//  HMSearchBar.swift
//  sinaweibo
//
//  Created by lst on 16/5/20.
//  Copyright © 2016年 lst. All rights reserved.
//

import UIKit

class HMSearchBar: UIView {

    @IBOutlet weak var searchTF: UITextField!
    @IBOutlet weak var cancelBtn: UIButton!
    
    @IBOutlet weak var rightCons: NSLayoutConstraint!
    class func loadSearchBar() -> HMSearchBar {
        let searchView = NSBundle.mainBundle().loadNibNamed("HMSearchBar", owner: nil, options: nil).last as! HMSearchBar
        
        return searchView
        
    }
   
    override func awakeFromNib() {
        //设置宽度
        //bounds.width中的width知识bounds的只读属性
        //要修改大小需要通过size进行修改
        self.bounds.size.width = ScreenWidth
        //文本输入框有leftView
        searchTF.leftView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        //设置显示模式
        searchTF.leftViewMode =
            .Always
        //修改frame
        searchTF.leftView?.frame = CGRect(x: 0, y: 0, width: 50, height: 40)
        //设置视图的显示模式
        searchTF.leftView?.contentMode = .Center    }
    
    @IBAction func textFiledBeginEditing(sender: AnyObject) {
        //修改约束
        //0.25 系统默认的动画事件
        UIView.animateWithDuration(0.25) {
            self.rightCons.constant = self.cancelBtn.bounds.width
            //提前强制刷新视图
            self.layoutIfNeeded()
        }
    }
    
    //关联 取消按钮点击事件 取消 textFiled编辑状态
    
    @IBAction func cancelBtnDidClick(sender: AnyObject) {
        //修改约束
        //收集约束的变化
        self.rightCons.constant = 0
        UIView.animateWithDuration(0.25) {
            //提前强制刷新视图
            //1.自动布局的视图 有frame 吗?  有frame
            //2.视图的frame 实在layoutSubviews方法中根据约束来设置
            //3.提前调用了layoutSubviews
            //更新视图的frame发生在 一个动画闭包中
            self.layoutIfNeeded()
        }
        
        
        //结束编辑状态
        //        searchTF.resignFirstResponder()
        self.endEditing(true)
    }
}
